
#! /usr/bin/python

import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
        self.info=[{"tipo":"Italiano","Calle":"lacalle"}]



    def _process(self):
	 pass
class MyOrganization(Federation.Federation):
    def _process(self):
    	#u=MyUnit(agent=self.myAgent, nick="gestor", name="supervision")
    	#self.addUnit(u)
	    time.sleep(2000)

class MyUnit(Unit.Hierarchy):
    def _process(self):
            mens=self.receiveMessage()
            while not mens:
              mens=self.receiveMessage()
            print mens
            content=[]
            for i in self.myAgent.info:
                if i["tipo"]==mens.getContent():
                    content.append(i)
            if content!=[]:
                ans=ACLMessage.ACLMessage()
                ans.setPerformative("inform")
                ans.setSender(self.myAgent.getAID())
                ans.addReceiver(mens.getSender())
                ans.setContent(str(content))
                self.sendPrivateMessage(ans,mens.getSender().getName())



if __name__ == "__main__":
    agent = "sitea@apolo.dsic.upv.es"
    #agent = "agent@thx1138.dsic.upv.es"
    #agent = "agent@tatooine.dsic.upv.es"
    b = Example(agent,"pasword")
    b.start()
    print "Agent "+agent+" registering"
    time.sleep(10)
    lista= b.getOrganizationList()
    print lista
    for i in lista:
        goal=b.getOrganizationInfo(i)["goal"]
        print goal
        g=eval(goal)
        if g.has_key("necesita") and "fuentes de informacion" in g["necesita"]:
            o=MyOrganization(b,nick="fuenteA", name=i)
            b.joinOrganization(o)
            l=o.getUnitList()
            print l
            for u in l:
                info=o.getUnitInfo(u)
                print info
                if info["type"]=="Hierarchy" and  "fuentes de informacion" in eval(info["goal"])["necesita"]:
                    u=MyUnit(b, nick="fuenteA", password="pass", name=u)
                    o.joinUnit(u)







